<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.itaoke.org All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author:  Caption <Caption@163.com> QQ 1674653
// +----------------------------------------------------------------------

namespace Wap\Controller;
use Common\Controller\FirstendController;

class SuperController extends FirstendController {
	
	public function _initialize() {
		parent::_initialize();
		$this->_mod = D('Items');
		$api_config = M('ItemsSite')->where(array('code' => 'itaoke'))->getField('config');
		$this->_tbconfig = unserialize($api_config);
	}
	
	private function tarnKeyword($keyword){
	    //如果是淘宝分享的关键词则自动匹配
	    if(strpos($keyword,'(' ) !==false || strpos($keyword,'（' ) !==false){
	        $result = array();
	        preg_match_all("/(?:()(.∗)(?:))/i",$keyword, $result);
	        if($result[1][0])
	           $keyword= $result[1][0];
	    }
	    return $keyword;
	}
	
	public function index(){
		$keyword=I('keyword');
		//如果是淘宝分享的关键词则自动匹配
		$keyword=getBetween($keyword,"（","）");
		$this->assign('random',$this->getRandom());
		$this->assign('items',$this->getToday());
		$this->assign('keyword',$keyword);
		$this->display();
	}
	
	/*
	 * 调用接口进行全网搜索
	 */
	public function search(){
	    $keyword=I('keyword');
	    $p=I('p',1);
		$keyword=getBetween($keyword,"（","）");
	    $this->assign('keyword',$keyword);
	    $this->assign('p',$p);
	//    $this->assign('items',$this->apiSearch($keyword,$p));
	    $this->display();
	}
	
	/**
	 * 调用api进行超级搜索
	 * @param unknown $keyword
	 * @param unknown $p
	 */
	public function apiSearch(){
	    $_r = array(
	        'status'=>0,
	        'data'=>'',
	        'count'=>0
	    );
	    
	    $keyword = I('keyword');
	    $p = I('p',1);
	    $taodianjin = C('itk_taojindian_html');
	    if (strpos($taodianjin, "text/javascript")) {
	        $pid = get_word($taodianjin, 'pid: "' , '"');
	    } else {
	        $pid = $taodianjin;
	    }
	    
	    $tb_top = $this->_get_itk_top();
	    $req = $tb_top->load_api('ItaokeItemsCouponGetRequest');
	    $req->setPid($pid);				
	    $req->setPageNo($p);
	    $req->setQ(base64_encode($keyword));
	    $resp = (array)$tb_top->execute($req);
	    if($resp['status'] == '0000')
	    {
	        $res = $resp['data'];
	    }
	    $count=0;
	    foreach ($res as $k=>$v){
	        $count++;
	        //取优惠券价格
	 //       $pos =strpos( $v['coupon_info'] ,'减');
	  //      $length = $pos + strlen('减');

	        $res[$k]['coupon_price'] = getBetween($v['coupon_info'] , '减','元');   //substr($v['coupon_info'], $length);
	        $res[$k]['after_price'] = $v['zk_final_price'] - $res[$k]['coupon_price']
	        ;
	    }
	    if($count > 0) $_r['status']=1;
	    $_r['count'] = $count;
	    $_r['data']=$res;

	    $this->ajaxReturn(0, '请求成功',$_r);

	}
	
	public function detail(){
		$num_iid=I('num_iid');
		$url=I('url');
		if($num_iid=='' && !$url){
			redirect(C('itk_wap_url'));
		}
		
		$res['pic_url']=I('pic_url');
		$res['title']=I('title');
		$res['num_iid']=$num_iid;
		$res['coupon_price']=I('price');
		$res['volume']=I('volume');
		$res['quan']= $res['coupon_price'] - I('after_price');
		$res['coupon_price']=I('price');
		$res['intro']='来自超级搜索,汇集全网优惠券,优惠多多哦~';
		$res['ulandUrl']=$url;
		
		$res['taotoken']=$this->_getTpwd($res['title'],$res['ulandUrl']);
		$this->_config_seo(C('itk_seo_config.item'), array(
			'title' => $res['title'],
			'intro' => $res['intro'],
			'price' => $res['price'],
			'coupon_price' => $res['coupon_price'],
			'seo_title' => $res['title'],
			'seo_keywords' => $res['title'],
			'seo_description' => $res['title'],
		));

		$this->assign('after',I('after_price'));
		$this->assign('random',$this->getRandom());
		$this->assign('item',$res);
		$this->display();
	}
	
	private function _getTpwd($title,$url){
	    $tb_top = $this->_get_itk_top();
	    $req = $tb_top->load_api('ItaokeTpwdCreateRequest');
	    $req->setText($title);				
	    $req->setUrl($url);
	    $resp = (array)$tb_top->execute($req);
	    if($resp['status'] != '0000')
	    {
	        return;
	    }
	    return $resp['data']['model'];	    
	}
	
	private function _get_itk_top() {
		vendor('Itaoke.TopClient');
		vendor('Itaoke.RequestCheckUtil');
		vendor('Itaoke.Logger');
		$top = new \TopClient;
		$top->appkey = $this->_tbconfig['app_key'];
		$top->secretKey = $this->_tbconfig['app_secret'];
		return $top;
	}
	
	/**
	 * 调用爱淘客api获取佣金淘口令
	 */
	private function transform($aprams){
		$taodianjin = C('itk_taojindian_html');
		if (strpos($taodianjin, "text/javascript")) {
			$pid = get_word($taodianjin, 'pid: "' , '"');
		} else {
			$pid = $taodianjin;
		}
		//鹊桥推广
		if($aprams['dx'] != 1 && C('itk_queqiao_pid')!=''){
			$pid = C('itk_queqiao_pid');
		}
		if (!$pid) {
			return;
		}
		$aprams['pid']=$pid;
		$tb_top = $this->_get_itk_top();
		$req = $tb_top->load_api('ItaokeTaotokenRequest');
		$req->setFields($aprams);				// 设置采集数据分类ID
		$resp = (array)$tb_top->execute($req);
		if($resp['status'] != '0000')
		{
			return;
		}
		return $resp['data'];
	}
	
	// 调用今日上新
	public function getToday(){
	    $items = M('Items');
	    $where['isq']=1;
	    $where['status']='underway';
	    $where['add_time']=array('EGT',strtotime(date('Y-m-d')));
	    $countcus=$items->where($where)->count();
	    $res=array();
	    $min=$items->where($where)->min('id');
	    $max=$items->where($where)->max('id');
	    if($countcus<$num){
	        $num=$countcus;
	    }
	    $i=1;
	    $flag=0;
	    while($i<=$num){
	        $rundnum=rand($min, $max);
	        if($flag!=$rundnum){
	            if($addlink=$items->getById($rundnum) ){
	                $res[]=$addlink;
	                $flag=$rundnum;
	                $i++;
	            }
	        }
	    }
	    if($res){
	        return $res;
	    }else{
	        return $this->getRandom(6);
	    }
	}
	
	public function getRandom($num=12){

		$items = M('Items');


		$where['isq']=1;
		$where['status']='underway';
		$countcus=$items->where($where)->count();

		$res=array();
		$min=$items->where($where)->min('id');
		$max=$items->where($where)->max('id');
		if($countcus<$num){
			$num=$countcus;
		}
		$i=1;
		$flag=0;
		while($i<=$num){
			$rundnum=rand($min, $max);
			if($flag!=$rundnum){
				if($addlink=$items->getById($rundnum) ){
					$res[]=$addlink;
					$flag=$rundnum;
					$i++;
				}
			}
		}
		return $res;
	}

	
}